package com.guwu.text_editor.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.guwu.text_editor.R;


public class CommentUtils implements ViewTreeObserver.OnGlobalLayoutListener {

    private static View rootView;
    private static PopupWindow popupWindow;
    int rootViewVisibleHeight;
    static boolean DisMiss = false;

    public CommentUtils(Activity activity) {
        rootView = activity.getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        int visibleHeight = r.height();
        if (rootViewVisibleHeight == 0){
            rootViewVisibleHeight = visibleHeight;
            return;
        }
        if (rootViewVisibleHeight == visibleHeight){
            return;
        }
        if (rootViewVisibleHeight - visibleHeight > 200){

            rootViewVisibleHeight = visibleHeight;
            return;
        }
        if (visibleHeight - rootViewVisibleHeight > 200){
            rootViewVisibleHeight = visibleHeight;
            if (!DisMiss){
                popupWindow.dismiss();
            }
            return;
        }
    }

    public static CommentUtils setListener(Activity activity){
        return new CommentUtils(activity);
    }

    public static Builder Builder(Context context){
        return new Builder(context);
    }
    public static Builder Builder(Context context,int anim){
        return new Builder(context,anim);
    }
    public static Builder Builder(Context context,int anim,int animD){
        return new Builder(context,anim,animD);
    }
   public static class Builder implements TextWatcher,View.OnClickListener {

        private final Context mContext;
       private  int mAnimD;
       private  int mAnim;
       private int mMaxNumber;
        private View mView;
        private EdChangInterface mEdChange;
       private CharSequence  mEmp;
       private int mStart;
       private int mEnd;
       private EditText mEditText;
       private TextView mTextView;
       private int mButtonId;
       private Button mButton;


       @Override
       public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
           mEmp = charSequence;
       }

       @Override
       public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

       }

       @Override
       public void afterTextChanged(Editable editable) {
           mStart = mEditText.getSelectionStart();
           mEnd   = mEditText.getSelectionEnd();
           mTextView.setText(String.valueOf(editable.length() + "/" + mMaxNumber));
           if (editable.length() > 0){
              mButton.setEnabled(true);
               DisMiss = true;
           }
           if (editable.length() <= 0){
              mButton.setEnabled(false);
               DisMiss = false;
           }
           if (editable.length() > mMaxNumber){
               if (mEdChange != null){
                   mTextView.setTextColor(Color.RED);
                   mEdChange.hintMsg();
               }
               editable.delete(mStart-1,mEnd);
               mEditText.setText(mEmp);
               mEditText.setSelection(editable.length());
               startAnim();
           }
           if (editable.length() < mMaxNumber){
               mTextView.setTextColor(Color.GRAY);
           }
       }

       /**
        * 开启输入达到最大数的效果  如 抖动
        */
       private void startAnim() {
           if (mAnimD > 0){
               Animation shake = AnimationUtils.loadAnimation(mContext,mAnimD);//加载动画资源文件
               mView.startAnimation(shake);
           }
       }

       @Override
       public void onClick(View view) {
           if (view.getId() == mButtonId){
               DisMiss = false;
               if (mEdChange != null){
                   mEdChange.getTextString(mEditText.getText().toString().trim());
               }
               mEditText.setText("");
               popDisMiss();
           }
       }

       public interface EdChangInterface{
            void getTextString(String string);
            void hintMsg();
        }

        public Builder(Context context) {
            this.mContext = context;
        }
        public Builder(Context context,int anim){
            this.mContext = context;
            this.mAnim = anim;
        }
        public Builder(Context context,int anim,int animD){
            this.mContext = context;
            this.mAnim = anim;
            this.mAnimD = animD;
        }

       /**
        * 添加布局
        * @param layoutId   布局id
        * @return
        */
        @SuppressLint("WrongConstant")
        public Builder setLayoutId(int layoutId){
            if (layoutId > 0){
                if (mView == null){
                    mView = LayoutInflater.from(mContext).inflate(layoutId, null);
                }
                if (popupWindow == null){
                    popupWindow = new PopupWindow(mView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
                }
                popupWindow.setTouchable(true);
                popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        return false;
                    }
                });
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setBackgroundDrawable(mView.getResources().getDrawable(R.drawable.ed_bg));
                popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                ColorDrawable cd = new ColorDrawable(0x000000);
                popupWindow.setBackgroundDrawable(cd);
                WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
                params.alpha = 0.4f;
                ((Activity)mContext).getWindow().setAttributes(params);
                popupWindow.setAnimationStyle(mAnim);
                popupWindow.update();
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        if (DisMiss){
                            showComment();
                        }else {
                            WindowManager.LayoutParams params = ((Activity) mView.getContext()).getWindow().getAttributes();
                            params.alpha = 1f;
                            ((Activity) mView.getContext()).getWindow().setAttributes(params);
                            if (popupWindow != null){
                                popupWindow.dismiss();
                                mEditText.setText("");
                            }
                        }

                    }
                });
            }
            return this;
        }

       /**
        * 显示PopWindow
        */
       private void showComment(){
            if (popupWindow != null && !popupWindow.isShowing()){
                popupWindow.showAtLocation(mView, Gravity.BOTTOM,0,0);
                InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }

       /**
        * 关闭PopWindow
        */
       private void popDisMiss(){
           if (popupWindow != null && popupWindow.isShowing()){
               popupWindow.dismiss();
           }
        }


       /**
        * 添加输入框
        * @param id Id
        * @return
        */
        public Builder addEditText(int id){
            if (id > 0){
                EditText mEd = getView(id);
                mEd.addTextChangedListener(this);
                mEditText = mEd;
            }
            return this;
        }

       public Builder addKeyHint(int id){

           return this;
       }




       public <T> T getView(int viewID) {
           return (T)mView.findViewById(viewID);
       }

       /**
        * 进行显示
        * @return
        */
        public Builder builder(){
            if (popupWindow != null && !popupWindow.isShowing()){
                popupWindow.showAtLocation(mView, Gravity.BOTTOM,0,0);
                InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return this;
        }

    }
}
